const { url } = require('inspector');
var config = require('./config');
var utils = require('./utils');

var moment = require('moment');
moment.locale('zh-cn');
class TDataPool {
    constructor() {
        this.config = config.config;
        this.utils = utils.utils;
    }

    getRealData_sd() {
            var me = this;
            var retData = {
                status: 0,
                data: {}
            }
            return new Promise((success, faild) => {
                try {
                    me.utils.httpCall(me.config.apis.sd.real, "POST").then(resData => {
                        try {
                            console.log(resData);
                            if (resData.result && resData.result != null) {
                                var resultDatas = JSON.parse(resData.result).realDatas;
                                resultDatas.forEach(r => {
                                    var inds = Object.values(me.config.inds);
                                    if (r.statusDev == "在线" && r.time.length > 10) {
                                        var rowTime = r.time;
                                        var mn = r.mn;
                                        if (!retData.data[mn]) {
                                            retData.data[mn] = {
                                                mn: mn,
                                                time: rowTime
                                            }
                                        }
                                        inds.forEach(ind => {
                                            var indKey = ind.k;
                                            var indValue = r[indKey];
                                            if (indValue != null && indValue > 0) {
                                                retData.data[mn][indKey] = indValue;
                                            } else {
                                                retData.data[mn][indKey] = 0;
                                            }
                                        })

                                    }
                                });
                                retData.status = 1;
                            }
                        } catch (eer) {
                            console.log(eer);
                        }
                        success(retData);
                    })
                } catch (er) {
                    console.log(er);
                    success(retData);
                }
            })
        }
        /*
            indKey:指标 co , no2
            timeFlag:1|24 , 
            dataVal :值 
        */
    getIqiValue(indKey, timeFlag, dataVal) {
        var res = 0;
        try {
            var iqis = me.config.iqiTab.filter(i => {
                var flag = i.ik == indKey && i.tf == timeFlag &&
                    i.il <= dataVal && i.ih > dataVal;
                return flag;
            });
            if (iqis.length > 0) {
                res = iqis[0].iqi;
            }
        } catch (er) {
            console.log(er);
        }
        return res;
    }
    getHisData_sd_Hour_mn(mn, start, end) {
        var me = this;
        var retData = {
            status: 0,
            data: {}
        }
        return new Promise((success, faild) => {
            try {
                var url = me.config.apis.sd.hour;
                url = url.replace("{start}", start);
                url = url.replace("{end}", end);
                url = url.replace("{mn}", mn);
                console.log('get hour data. mn:%s , from:%s , to:%s', mn, start, end);
                me.utils.httpCall(url, "POST").then(resData => {
                    try {
                        if (resData.result && resData.result != null) {
                            var resultDatas = JSON.parse(resData.result).realDatas;
                            resultDatas.forEach(r => {
                                var inds = Object.values(me.config.inds);
                                if (r.time && r.time != null && r.time.length > 10) {
                                    var rowTime = r.time;
                                    var timestp = (new Date(rowTime)).getTime();
                                    var rowKey = mn + "_" + rowTime;
                                    if (!retData.data[rowKey]) {
                                        retData.data[rowKey] = {
                                            rowKey: rowKey,
                                            mn: mn,
                                            time: rowTime,
                                            timestp: timestp
                                        }
                                    }
                                    inds.forEach(ind => {
                                        var indKey = ind.k;
                                        var indValue = r[indKey];
                                        if (indValue != null && indValue > 0) {
                                            retData.data[rowKey][indKey] = indValue;
                                        }
                                    })

                                }
                            });
                            retData.status = 1;
                        }
                    } catch (eer) {
                        console.log(eer);
                    }
                    success(retData);
                })
            } catch (er) {
                console.log(er);
                success(retData);
            }
        })
    }
    getHisData_sd_Hour(start, end) {
        var me = this;
        var retData = {
            status: 0,
            data: []
        }
        return new Promise((success, faild) => {
            try {
                me.utils.httpCall(me.config.apis.sd.real, "POST").then(resData => {
                    try {
                        console.log(resData);
                        if (resData.result && resData.result != null) {
                            var resultDatas = JSON.parse(resData.result).realDatas;
                            var loadItem = () => {
                                if (resultDatas.length > 0) {
                                    var r = resultDatas.shift();
                                    me.getHisData_sd_Hour_mn(r.mn, start, end).then(_res => {
                                        var msDatas = _res.status == 1 ? Object.values(_res.data) : [];
                                        msDatas.forEach(d => {
                                            retData.data.push(d);
                                        })
                                        loadItem();
                                    })
                                } else {
                                    retData.status = 1;
                                    success(retData);
                                }
                            }
                            loadItem();
                        }
                    } catch (eer) {
                        console.log(eer);
                    }
                })
            } catch (er) {
                console.log(er);
                success(retData);
            }
        })
    }
    getHisData_sd_Hour_dataFile(start, end) {
        var me = this;
        var retData = {
            status: 0,
            data: []
        }
        return new Promise((success, faild) => {
            try {
                me.getHisData_sd_Hour(start, end).then(_resData => {
                    if (_resData.status > 0) {
                        var dbUrl = me.config.db.dbUrl;
                        var dbName = me.config.db.dbName;
                        var tableName = "T_H";
                        var tags = {};
                        var fields = {};
                        var timestampe = 0;
                        var inds = Object.values(me.config.inds);
                        var contentItems = [];
                        for (var i = 0; i < _resData.data.length; i++) {
                            var r = _resData.data[i];
                            var content = "";
                        }

                        var loadItem = () => {
                            try {
                                var r = _resData.data.shift();
                                tags = {
                                    mn: r.mn
                                };
                                fields = {};
                                inds.forEach(ind => {
                                    if (r[ind.k] && r[ind.k] != null && r[ind.k] > 0) {
                                        fields[ind.k] = r[ind.k];
                                    }
                                });
                                timestampe = r.timestp * 1000 * 1000;
                                me.utils.writeDB(dbUrl, dbName, tableName, tags, fields, timestampe).then(_r => {
                                    loadItem();
                                })
                            } catch (err) {
                                console.log(err);
                                loadItem();
                            }
                        }
                        loadItem();
                    } else {
                        success();
                    }
                })
            } catch (er) {
                console.log(er);
                success(retData);
            }
        })
    }
    writeHisData_sd_Hour(start, end) {
        var me = this;
        var retData = {
            status: 0,
            data: []
        }
        return new Promise((success, faild) => {
            try {
                me.getHisData_sd_Hour(start, end).then(_resData => {
                    if (_resData.status > 0) {
                        var dbUrl = me.config.db.dbUrl;
                        var dbName = me.config.db.dbName;
                        var tableName = "T_H";
                        var tags = {};
                        var fields = {};
                        var timestampe = 0;
                        var inds = Object.values(me.config.inds);
                        var loadItem = () => {
                            try {
                                var r = _resData.data.shift();
                                tags = {
                                    mn: r.mn
                                };
                                fields = {};
                                inds.forEach(ind => {
                                    if (r[ind.k] && r[ind.k] != null && r[ind.k] > 0) {
                                        fields[ind.k] = r[ind.k];
                                    }
                                });
                                timestampe = r.timestp * 1000 * 1000;
                                me.utils.writeDB(dbUrl, dbName, tableName, tags, fields, timestampe).then(_r => {
                                    loadItem();
                                })
                            } catch (err) {
                                console.log(err);
                                loadItem();
                            }
                        }
                        loadItem();
                    } else {
                        success();
                    }
                })
            } catch (er) {
                console.log(er);
                success(retData);
            }
        })
    }
    getBeforeMeanData_hour(start, end) {
        var me = this;
        var retData = {
            status: 0,
            data: []
        }
        return new Promise((success, faild) => {
            try {
                var tasks = [];
                var step = 1 * 3600 * 1000;
                var from = (new Date(start)).getTime();
                if (start.indexOf('+08') < 0) {
                    from -= 8 * 3600 * 1000;
                }
                var to = (new Date(end)).getTime();
                if (end.indexOf('+08') < 0) {
                    to -= 8 * 3600 * 1000;
                }
                var current = from;
                while (current < to) {
                    var task = {
                        endTm: current,
                        startTm_8h: current - 8 * 3600 * 1000,
                        startTm_24h: current - 24 * 3600 * 1000,
                        endTm_str: moment(current).format('YYYY-MM-DD HH:00:00'),
                        startTm_8h_str: moment(current - 8 * 3600 * 1000).format('YYYY-MM-DD HH:00:00'),
                        startTm_24h_str: moment(current - 24 * 3600 * 1000).format('YYYY-MM-DD HH:00:00'),
                    };
                    tasks.push(task);
                    current += step;
                }
                console.log(tasks);
                var queryO38 = (task) => {
                    return new Promise((s, f) => {
                        try {
                            var sqlFormat = "select mean(o3) as o3_8h from T_H where  time >= '{start}' and time<'{end}' group by mn  TZ('Asia/Shanghai')";
                            if (!task['queryDatas']) {
                                task['queryDatas'] = {};
                            }
                            var dataSql = sqlFormat;
                            dataSql = dataSql.replace('{start}', task.startTm_8h_str);
                            dataSql = dataSql.replace('{end}', task.endTm_str);
                            var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName + "&q=" + dataSql;
                            me.utils.httpCall(url, "GET").then(_res => {
                                try {
                                    var resData = JSON.parse(_res.result);
                                    var flag = resData.results && resData.results != null &&
                                        resData.results.length > 0 &&
                                        resData.results[0].series && resData.results[0].series != null && resData.results[0].series.length > 0;
                                    if (flag) {
                                        resData.results[0].series.forEach(s => {
                                            var sFlag = s.values && s.values.length > 0 && s.values[0] && s.values[0].length > 0;
                                            if (sFlag) {
                                                var mn = s.tags.mn;
                                                var tm = task.endTm_str;
                                                var val = s.values[0][1];
                                                if (!task['queryDatas'][mn + '_' + tm]) {
                                                    task['queryDatas'][mn + '_' + tm] = {
                                                        k: mn + '_' + tm,
                                                        mn: mn,
                                                        tm: tm
                                                    };
                                                }
                                                task['queryDatas'][mn + '_' + tm].o3_8h = val;
                                            }
                                        })
                                    }
                                } catch (eer) {
                                    console.log(eer);
                                }
                                s(task);
                            });
                        } catch (ee) {
                            console.log(ee);
                            s();
                        }
                    })
                };
                var queryPm24H = (task) => {
                    return new Promise((s, f) => {
                        try {
                            var sqlFormat = "select mean(pm10) as pm10_24h,mean(pm25) as pm25_24h from T_H where  time >= '{start}' and time<'{end}' group by mn  TZ('Asia/Shanghai')";
                            if (!task['queryDatas']) {
                                task['queryDatas'] = {};
                            }
                            var dataSql = sqlFormat;
                            dataSql = dataSql.replace('{start}', task.startTm_24h_str);
                            dataSql = dataSql.replace('{end}', task.endTm_str);
                            var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName + "&q=" + dataSql;
                            me.utils.httpCall(url, "GET").then(_res => {
                                try {
                                    var resData = JSON.parse(_res.result);
                                    var flag = resData.results && resData.results != null &&
                                        resData.results.length > 0 &&
                                        resData.results[0].series && resData.results[0].series != null && resData.results[0].series.length > 0;
                                    if (flag) {
                                        resData.results[0].series.forEach(s => {
                                            var sFlag = s.values && s.values.length > 0 && s.values[0] && s.values[0].length > 0;
                                            if (sFlag) {
                                                var mn = s.tags.mn;
                                                var tm = task.endTm_str;
                                                var pm10Val = s.values[0][1];
                                                var pm25Val = s.values[0][2];
                                                if (!task['queryDatas'][mn + '_' + tm]) {
                                                    task['queryDatas'][mn + '_' + tm] = {
                                                        k: mn + '_' + tm,
                                                        mn: mn,
                                                        tm: tm
                                                    };
                                                }
                                                task['queryDatas'][mn + '_' + tm].pm10_24h = pm10Val;
                                                task['queryDatas'][mn + '_' + tm].pm25_24h = pm25Val;
                                            }
                                        })
                                    }
                                } catch (eer) {
                                    console.log(eer);
                                }
                                s(task);
                            });
                        } catch (ee) {
                            console.log(ee);
                            s();
                        }
                    })
                };

                var index = 0;
                var loadItem = () => {
                    if (index < tasks.length) {
                        var t = tasks[index];
                        queryO38(t).then(_ => {
                            return queryPm24H(t);
                        }).then(_ => {
                            index++;
                            loadItem();
                        })
                    } else {
                        tasks.forEach(task => {
                            Object.values(task.queryDatas).forEach(r => {
                                var row = {
                                    tableName: "T_H",
                                    timestampe: task.endTm * 1000 * 1000,
                                    tags: {
                                        mn: r.mn
                                    },
                                    fields: {
                                        o3_8h: r.o3_8h && r.o3_8h != null ? r.o3_8h : 0,
                                        pm10_24h: r.pm10_24h && r.pm10_24h != null ? r.pm10_24h : 0,
                                        pm25_24h: r.pm25_24h && r.pm25_24h != null ? r.pm25_24h : 0
                                    }
                                }
                                retData.data.push(row);
                            })
                        })
                        retData.status = 1;
                        success(retData);
                    }
                }

                loadItem();

            } catch (er) {
                console.log(er);
                success(retData);
            }
        })
    }
    writeBeforeMeanData_hour(start, end) {
        var me = this;
        var retData = {
            status: 0,
            data: []
        }
        return new Promise((success, faild) => {
            try {
                me.getBeforeMeanData_hour(start, end).then(_res => {
                    var rows = _res.data;
                    return me.utils.writeBatchDB(me.config.db.dbUrl, me.config.db.dbName, rows);
                }).then(_r => {
                    console.log(_r);
                })
            } catch (er) {
                console.log(er);
                success(retData);
            }
        })
    }


}


var pool = new TDataPool();
console.log(pool.config);
pool.writeBeforeMeanData_hour('2021-11-04', '2021-11-08').then(_r => {
        console.log(_r);
    })
    /*
    pool.writeHisData_sd_Hour('2021-11-06', '2021-11-09').then(res => {
        console.log(res);
    })
    */